package top.dark.product.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.dark.common.exception.BizCodeEnum;
import top.dark.common.utils.R;
import java.util.HashMap;
import java.util.Map;

/**
 * Author: Darkn
 * description:
 * Create Time: 2021/2/20 11:16
 */
@Slf4j
@RestControllerAdvice(basePackages = "top.dark.product.controller")
public class GlobalException {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        log.error("数据校验异常：{}，异常类型：{}", e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item)->{
            errorMap.put(item.getField(), item.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data", errorMap);
    }

//    @ExceptionHandler(value = Exception.class)
//    public R handleException(Exception e) {
//        log.error("全局异常：{}，异常类型：{}", e.getMessage(), e.getClass());
//        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
//    }
}
